package com.zcyr.controller;

import com.zcyr.core.AbstractDatabaseEnvironment;
import com.zcyr.core.AbstractDatabaseEnvironmentManager;
import com.zcyr.exception.CommandExecutorException;
import com.zcyr.exception.DatabaseEnvironmentException;
import com.zcyr.exception.DatabaseEnvironmentManagerException;
import com.zcyr.pojo.UserInfo;
import com.zcyr.service.DemoService;
import com.zcyr.util.JsonBody;
import com.zcyr.util.TokenTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.*;
import java.util.Map;


/**
 * @author zcyr
 */
@CrossOrigin(allowCredentials = "true")
@RestController
@RequestMapping("sql")
public class DemoController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DemoService service;

    @Autowired
    private AbstractDatabaseEnvironmentManager databaseEnvironmentManager;

    @Autowired
    private HttpServletRequest request;

    /**
     * 执行sql接口
     *
     * @param map {
     *            #要执行的sql语句
     *            sql: String
     *            }
     * @return {
     * #返回的执行结果
     * metadata: HashMap<String, String>
     * data: HashMap<String, String>
     * }
     */
    @RequestMapping(value = "/execute", method = {RequestMethod.POST})
    public JsonBody execute(@RequestBody Map<String, String> map) throws SQLException, DatabaseEnvironmentException, CommandExecutorException, DatabaseEnvironmentManagerException {
        HttpSession session = request.getSession(false);
        AbstractDatabaseEnvironment environment = databaseEnvironmentManager.getEnvironment((String) session.getAttribute("environmentUUID"));
        if (environment == null){
            UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");

            logger.info(String.format("正在为用户(%s)取得数据库环境...", userInfo.getName()));

            environment = databaseEnvironmentManager.getAvailableEnvironment();
            session.setAttribute("environmentUUID", environment.getUuid());

            logger.info(String.format("为用户(%s)取得数据库环境成功 环境id: %s", userInfo.getName(), environment.getUuid()));
        }

        return service.executeSQL(
                environment,
                map.get("sql"));
    }

    @RequestMapping("/newEnv/{token}")
    public JsonBody reConnect(@PathVariable("token") String token) throws DatabaseEnvironmentManagerException {
        HttpSession session = request.getSession(false);
        String tokenNewEnv = (String) session.getAttribute("token-newEnv");
        if (tokenNewEnv != null && TokenTool.getAndDel(tokenNewEnv) != null){
            AbstractDatabaseEnvironment environment = databaseEnvironmentManager.getEnvironment((String) session.getAttribute("environmentUUID"));

            session.setAttribute("environmentUUID",
                    databaseEnvironmentManager.reportErrorEnvironment(environment));

            session.setAttribute("token-newEnv", null);
            return JsonBody.ok("成功获取到新数据库环境!");
        }
        return JsonBody.error("无法重复获取新数据库环境.");
    }
}
